package com.study.group.common.token;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.study.group.common.result.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description 自定义拦截器
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2019/3/22 17:45
 * @Version     v1
 **/
@Component
@Configuration
public class JwtIntercept implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(JwtIntercept.class);
    private static final String TOKEN_NAME = "Authorization";
    private static final String PRE_TOKEN = "Bearer";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader(TOKEN_NAME);
            logger.info("===== interceptor ===== token:{}",token);
            if(StringUtils.isEmpty(token)){
                printResponse(response, "token不能为空");
                return false;
            }
            if(!token.contains(PRE_TOKEN)){
                printResponse(response, "token不合法");
                return false;
            }
            //截取掉前缀
            String tokenNew = token.substring(7);
            boolean tokenExpired = JwtUtil.isTokenExpired(tokenNew);
            if(tokenExpired){
                printResponse(response, "token已失效");
                return false;
            }else{
                String id = JwtUtil.getId(tokenNew);
                /*if(!StringUtils.isEmpty(id)){
                    Cuser cuser = paramService.userGetById(Integer.parseInt(id));
                    if(null == cuser){
                        printResponse(response, "token不合法");
                        return false;
                    }
                }*/
                request.setAttribute("userId", id);
                return true;
            }
        } catch (JWTDecodeException e) {
            printResponse(response, "token解析失败");
            return false;
        } catch (Exception e){
            printResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"服务器异常");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

    /**
     * 输出错误信息
     * @param response
     * @param msg
     * @throws Exception
     */
    private void printResponse(HttpServletResponse response, String msg) throws Exception{
        ResponseResult data = new ResponseResult();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        data.setCode(HttpServletResponse.SC_UNAUTHORIZED);
        data.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        data.setSuccess(false);
        data.setMsg(msg);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSONObject.toJSONString(data));
        out.flush();
        out.close();
    }

    /**
     * 输出错误信息
     * @param response
     * @param msg
     * @throws Exception
     */
    private void printResponse(HttpServletResponse response, int code, String msg) throws Exception{
        ResponseResult data = new ResponseResult();
        data.setCode(code);
        data.setSuccess(false);
        data.setMsg(msg);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSONObject.toJSONString(data));
        out.flush();
        out.close();
    }

}
